<template>
    <div>
        <!-- 数据字典管理 -->
        <el-card style="height: 6000px" class="card">
            <div slot="header">
                <span>数据字典管理</span>
            </div>
            <el-row>
                <!-- 查询栏 -->
                <el-form :inline="true" :model="searchModel">
                    <el-form-item>
                        <!-- <el-input placeholder="输入关键字查询" v-model="searchModel.dict" clearable maxlength="20" /> -->
                        <el-autocomplete
                            clearable
                            class="inline-input"
                            v-model="searchModel.dict"
                            :fetch-suggestions="querySearch"
                            placeholder="输入关键字查询"
                            @select="handleSelect"
                            ></el-autocomplete> 
                            <!-- :trigger-on-focus="false" -->
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="submitSearchModel">查询</el-button>
                        <el-button type="success" @click="createNewDict">新增数据字典</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <!-- 树状图显示查询结果 -->
                <div class="block">
                    <el-tree
                        :data="dictListMenus"
                        :props="menusProps"
                        accordion
                        node-key="code"
                        ref="tree"
                        :auto-expand-parent="false"
                        :expand-on-click-node="false"
                        :default-expand-all="false"
                        :style="{ overflow: 'auto', height: treeHeight }"
                    >
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span>{{ node.label }}</span>
                            <span>
                                <el-button type="text" size="mini" @click="() => append(data)"> 添加 </el-button>
                                <el-button type="text" size="mini" @click="() => edit(node, data)"> 编辑 </el-button>
                                <el-button type="text" size="mini" @click="() => remove(node, data)"> 删除 </el-button>
                            </span>
                        </span>
                    </el-tree>
                </div>
            </el-row>
            <el-row>
                <!-- 子结点--编辑弹出框 -->
                <el-dialog title="数据" :visible.sync="editVisible" width="50%">
                    <el-form :model="form" ref="form" label-width="120px">
                        <!-- 自定义编辑内容样式 -->
                        <el-col :span="16">
                            <el-form-item :label="form.itemName">
                                <el-input v-model="form.itemValue"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 此处还可以添加内容 -->
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="editVisible = false">取 消</el-button>
                        <el-button type="primary" @click="save" v-if="isNewData">确 定</el-button>
                        <el-button type="primary" @click="save" v-else>确 定</el-button>
                    </span>
                </el-dialog>
            </el-row>
            <el-row>
                <!-- 新结点--编辑弹出框 -->
                <el-dialog title="数据" :visible.sync="editVisible2" width="50%">
                    <el-form :model="form2" ref="form2" label-width="120px">
                        <!-- 自定义编辑内容样式 -->
                        <el-col :span="16">
                            <el-form-item :label="form2.newItemName1">
                                <el-input v-model="form2.itemName"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="16">
                            <el-form-item :label="form2.newItemName2">
                                <el-input v-model="form2.itemValue"></el-input>
                            </el-form-item>
                        </el-col> -->
                        <!-- 此处还可以添加内容 -->
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="editVisible2 = false">取 消</el-button>
                        <el-button type="primary" @click="saveNew">确 定</el-button>
                    </span>
                </el-dialog>
            </el-row>
            <el-row>
                <!-- 编辑修改--编辑弹出框 -->
                <el-dialog title="数据修改" :visible.sync="editVisible3" width="50%">
                    <el-form :model="form2" ref="form3" label-width="120px">
                        <!-- 自定义编辑内容样式 -->
                        <el-col :span="16" v-if="isNode">
                            <el-form-item :label="form3.name">
                                <el-input v-model="form3.itemName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16" v-else>
                            <el-form-item :label="form3.itemName">
                                <el-input v-model="form3.itemValue"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 此处还可以添加内容 -->
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="editVisible3 = false">取 消</el-button>
                        <el-button type="primary" @click="saveEdit">修 改</el-button>
                    </span>
                </el-dialog>
            </el-row>
        </el-card>
    </div>
</template>

<script>
import {
    ListAllDataDicts,
    InsertDataDict,
    InsertDataDictItem,
    EditOneDataDict,
    EditOneDataDictItem,
    DeleteOneDataDict,
    DeleteOneDataDictItem,
    ListAllDataDictsByCondition
} from '../../../api/module/systemManagement/DataDictManagement';
let code = 1000;
export default {
    data() {
        return {
            //查询条件
            searchModel: {
                dict: ''
            },
            //查询结果--树状图显示
            dictListMenus: [],
            //将name（key）的值（value）变为label的值
            menusProps: {
                children: 'children',
                label: 'itemName' //name
            },
            defaultExpandedKeys: [],
            treeHeight: '',
            editVisible: false,
            form: {},
            isNewData: true,
            //新结点--数据
            editVisible2: false,
            form2: {},
            //编辑--数据
            editVisible3: false,
            isNode: false,
            form3: {},
            //查询过滤数据
            filtersList: [],
            //模拟数据
            data: [
                {
                    code: '0001',
                    itemName: '性别',
                    children: [
                        {
                            code: '000101',
                            itemName: '男',
                            children: []
                        },
                        {
                            code: '000102',
                            itemName: '女'
                        }
                    ]
                },
                {
                    code: '0002',
                    itemName: '性别',
                    children: [
                        {
                            code: '000101',
                            itemName: '男',
                            children: [
                                {
                                    code: '00010101',
                                    itemName: '三级 1-1-1'
                                },
                                {
                                    code: '00010102',
                                    itemName: '三级 1-1-2'
                                }
                            ]
                        },
                        {
                            code: '000102',
                            itemName: '女'
                        }
                    ]
                }
            ]
        };
    },
    created() {
        // this.getHeight()
        this.ListAllDataDicts();
    },
    mounted() {},
    methods: {
        //过滤
        querySearch(queryString, cb) {
            var filtersList = this.filtersList;
            var results = queryString ? filtersList.filter(this.createFilter(queryString)) : filtersList;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (filtersList) => {
            return (filtersList.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        loadAll() {
            return this.filtersList
        },
        handleSelect(item) {
            // console.log(item);
        },
        //获取树（菜单）的高度
        getHeight() {
            let height = window.innerHeight;
            let width = window.innerWidh;
            this.treeHeight = height + 600 + 'px';
        },
        //获得所有数据字典
        ListAllDataDicts() {
            ListAllDataDicts().then((res) => {
                // console.log(res.data)
                this.filtersList = []
                this.dictListMenus = []
                var count = 0;
                var i = 0;
                for (var key in res.data) {
                    var item1 = {
                        code: '',
                        itemName: '',
                        children: []
                    };
                    item1.code = key;
                    if (res.data[key].length != 0) {
                        item1.itemName = res.data[key][0].itemName;
                    }
                    //第一次赋值
                    this.dictListMenus[i] = item1;
                    var filtersItem = {
                        'value': item1.itemName,
                        'address': ''
                    }
                    this.filtersList[i] = filtersItem
                    var j = 0;
                    var j_max = res.data[key].length;
                    var temp = key;
                    for (j = 0; j < j_max; j++) {
                        temp = temp + '1';
                        var item2 = {
                            code: '',
                            itemName: '',
                            children: []
                        };
                        item2.code = temp;
                        item2.itemName = res.data[key][j].itemValue;
                        this.dictListMenus[i].children[j] = item2;
                    }
                    count++;
                    i++;
                }
                //更新触发
                this.dictListMenus = JSON.parse(JSON.stringify(this.dictListMenus));
            });
        },
        //查询某个数据字典--条件查询
        ListAllDataDictsByCondition(keyWord) {
            ListAllDataDictsByCondition(keyWord).then((res) => {
                // console.log(res.data)   
                // this.filtersList = []
                var dictListMenus = []
                var count = 0;
                var i = 0;
                for (var key in res.data) {
                    var item1 = {
                        code: '',
                        itemName: '',
                        children: []
                    };
                    item1.code = key;
                    if (res.data[key].length != 0) {
                        item1.itemName = res.data[key][0].itemName;
                    }
                    //第一次赋值
                    dictListMenus[i] = item1;
                    // var filtersItem = {
                    //     'value': item1.itemName,
                    //     'address': ''
                    // }
                    // this.filtersList[i] = filtersItem
                    var j = 0;
                    var j_max = res.data[key].length;
                    var temp = key;
                    for (j = 0; j < j_max; j++) {
                        temp = temp + '1';
                        var item2 = {
                            code: '',
                            itemName: '',
                            children: []
                        };
                        item2.code = temp;
                        item2.itemName = res.data[key][j].itemValue;
                        dictListMenus[i].children[j] = item2;
                    }
                    count++;
                    i++;
                }
                // console.log(count)
                //更新触发
                this.dictListMenus = JSON.parse(JSON.stringify(dictListMenus));
                // console.log(this.dictListMenus)
                // console.log(this.filtersList) 
            });
        },
        //插入一个数据字典
        InsertDataDict(itemName) {
            InsertDataDict(itemName).then((res) => {
                console.log(res);
                this.$message.success(`数据插入成功！`);
                //页面显示插入数据（查询）
                this.ListAllDataDicts();
            });
        },
        //插入一个数据字典的item
        InsertDataDictItem(itemName, itemValue) {
            InsertDataDictItem(itemName, itemValue).then((res) => {
                console.log(res);
                if (res.code == '212') {
                    this.$message.success(`当前数据已经存在！`);
                } else {
                    this.$message.success(`数据插入成功！`);
                    //页面显示插入数据（查询）
                    this.ListAllDataDicts();
                }
            });
        },
        //修改一个数据字典
        EditOneDataDict(code, itemName) {
            EditOneDataDict(code, itemName).then((res) => {
                console.log(res);
                this.$message.success(`数据修改成功！`);
                //页面显示插入数据（查询）
                this.ListAllDataDicts();
            });
        },
        //修改一个数据字典的item
        EditOneDataDictItem(itemName, oldItemValue, newItemValue) {
            EditOneDataDictItem(itemName, oldItemValue, newItemValue).then((res) => {
                console.log(res);
                if (res.code == '212') {
                    this.$message.success(`当前数据已经存在！`);
                } else {
                    this.$message.success(`数据修改成功！`);
                    //页面显示插入数据（查询）
                    this.ListAllDataDicts();
                }
            });
        },
        //删除一个数据字典
        DeleteOneDataDict(code) {
            DeleteOneDataDict(code).then((res) => {
                console.log(res);
                this.$message.success(`数据删除成功！`);
                //页面显示插入数据（查询）
                this.ListAllDataDicts();
            });
        },
        //删除一个数据字典的item
        DeleteOneDataDictItem(code, itemValue) {
            DeleteOneDataDictItem(code, itemValue).then((res) => {
                console.log(res);
                this.$message.success(`数据删除成功！`);
                //页面显示插入数据（查询）
                this.ListAllDataDicts();
            });
        },
        //点击查询事件--查询（条件）
        submitSearchModel() {
            // 从原来查询的结果中把数据筛选出来
            if(this.searchModel.dict == '' || this.searchModel.dict == null) {
                this.ListAllDataDicts();
            } else {
                // this.ListAllDataDicts();
                this.ListAllDataDictsByCondition(this.searchModel.dict)
            }
            this.$message.success(`查询成功！`);
        },
        //树点击事件
        handleNodeClick() {},
        //添加节点--新结点
        createNewDict() {
            this.editVisible2 = true;
            this.form2 = {
                newItemName1: '新数据字典名称',
                newItemName2: '数据字典数据',
                itemName: '',
                itemValue: ''
            };
        },
        //添加结点--子结点
        append(data) {
            // console.log(data)
            //如果有子节点（有-添加，无-不能添加）
            if (data.children.length != 0 || data.code.length <= 4) {
                this.editVisible = true;
                this.isNewData = true;
                this.form = {
                    code: data.code,
                    itemName: data.itemName
                };
            } else {
                // this.$message.error(`该结点无法添加数据！`)
                console.log('该结点无法添加数据！');
            }
        },
        //编辑--结点
        edit(node, data) {
            // console.log(node, data)
            this.editVisible3 = true;
            //如果有子节点
            if (data.children.length != 0 || data.code.length <= 4) {
                this.isNode = true;
                this.form3 = {
                    name: '数据字典名称',
                    code: data.code,
                    itemName: data.itemName
                };
            } else {
                this.isNode = false;
                this.form3 = {
                    code: node.parent.data.code,
                    itemName: node.parent.data.itemName,
                    oldItemValue: data.itemName,
                    itemValue: data.itemName
                };
            }
        },
        //删除--结点
        remove(node, data) {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    //页面显示效果
                    const parent = node.parent;
                    const children = parent.data.children || parent.data;
                    const index = children.findIndex((d) => d.code === data.code);
                    children.splice(index, 1);
                    //删除数据库数据操作
                    //删除结点--实际
                    if (data.children.length != 0) {
                        //表示删除一个数据字典
                        this.DeleteOneDataDict(data.code);
                    } else {
                        //表示删除一个数据字典的item
                        this.DeleteOneDataDictItem(node.parent.data.code, data.itemName);
                    }
                })
                .catch(() => {});
        },
        //保存--（新结点）
        saveNew() {
            this.editVisible2 = false;
            // console.log(this.form2)
            if (this.form2.itemName != '') {
                //数据库新增数据
                this.InsertDataDict(this.form2.itemName);
            } else {
                this.$message.error(`数据插入失败！`);
            }
        },
        //保存--编辑、新增（子结点）
        save() {
            this.editVisible = false;
            //如果是新增
            if (this.isNewData) {
                this.InsertDataDictItem(this.form.itemName, this.form.itemValue);
            } else {
                //数据修改
            }
        },
        //修改--结点数据
        saveEdit() {
            this.editVisible3 = false;
            //数据库编辑操作
            if (this.isNode) {
                //如果是结点
                this.EditOneDataDict(this.form3.code, this.form3.itemName);
            } else {
                //如果是子结点
                this.EditOneDataDictItem(this.form3.itemName, this.form3.oldItemValue, this.form3.itemValue);
            }
        },
        //点击结点
        renderContent(h, { node, data, store }) {
            return (
                <span class="custom-tree-node">
                    <span>{node.label}</span>
                    <span>
                        <el-button size="mini" type="text" on-click={() => this.append(data)}>
                            添加
                        </el-button>
                        <el-button size="mini" type="text" on-click={() => this.remove(node, data)}>
                            删除
                        </el-button>
                    </span>
                </span>
            );
        }
    },
    computed: {
        // dictList() {
        //   return this.dictListMenus.filter((item) => {
        //       return item.indexOf(this.searchModel.dict) !== -1;
        //   })
        // }
    }
};
</script>

<style>
.card >>> .el-card__body {
    padding: 5px;
}
.card >>> .el-card__header {
    font-size: 17px;
    padding: 5px 10px;
    /* padding: 5px 10px !important; */
    height: 40px;
    line-height: 30px;
    background-color: #eef0f6;
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
.block {
    width: 100%;
}
</style>